package com.suzhiliang.springbootlesson.securityOAuth2;

import com.suzhiliang.springbootlesson.mybatisToCRUD.User;
import com.suzhiliang.springbootlesson.mybatisToCRUD.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Copyright (C), 2015-2019, XXX有限公司
 *
 * @ClassName: SzlUserDetailsService
 * @Author: xmm
 * @Date: 2019/7/22 16:36
 * @Description: 自定义UserDetailsService
 * @Version 1.0
 */
@Component("szlUserDetailsService")
public class SzlUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //获取用户信息
        User userInfo = userMapper.findUserByUserName(userName);

        if(userInfo == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //获取用户对应角色名称
        List<String> roleNames = userMapper.selectRoleNamesByUserId(userInfo.getId());
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String roleName:roleNames){
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(roleName);
            grantedAuthorities.add(grantedAuthority);
        }

        // 封装用户信息，并返回。参数分别是：用户名，密码，用户权限
        org.springframework.security.core.userdetails.User user
                = new  org.springframework.security.core.userdetails.
                User(userName, userInfo.getPassword(),
                grantedAuthorities);
        return user;
    }

}
